﻿#region File Header
// Copyright (c) 2011, Stefan Stolz
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// 
// * Neither the name of Sharp2City nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
#region using directives

using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Linq;

using SampleApplication.Properties;

using Sharp2City;
using System.Globalization;

#endregion

namespace SampleApplication
{
    public partial class FormMain : Form, ITeamCityAccessConfiguration
    {
        #region private fields

        private readonly TeamCityClient teamCityClient;

        #endregion

        #region constructors

        public FormMain()
        {
            this.InitializeComponent();

            this.teamCityClient = new TeamCityClient(this);
        }

        #endregion

        #region protected override methods

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            Settings.Default.Save();

            base.OnFormClosed(e);
        }

        #endregion

        #region private methods

        private void OnButtonShowServerInfoClick(object sender, EventArgs e)
        {
            this.SafeExecute(this.ShowServerInfo);
        }

        private void SafeExecute(Action action)
        {
            try
            {
                action();
            }
            catch (Exception exception)
            {
                MessageBox.Show(this,
                                exception.Message,
                                this.Text,
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }

        private void ShowServerInfo()
        {
            ServerInfo serverInfo = this.teamCityClient.ServerInfo;

            StringBuilder message = new StringBuilder();

            message.AppendFormat("Version: {0}", serverInfo.Version).AppendLine();
            message.AppendFormat("StartTime: {0}", serverInfo.StartTime).AppendLine();
            message.AppendFormat("CurrentTime: {0}", serverInfo.CurrentTime).AppendLine();

            MessageBox.Show(message.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #endregion

        #region ITeamCityAccessConfiguration Members

        string ITeamCityAccessConfiguration.HostName
        {
            [DebuggerStepThrough]
            get
            {
                return (this.textBoxHostName.Text);
            }
        }

        string ITeamCityAccessConfiguration.Password
        {
            [DebuggerStepThrough]
            get
            {
                return (this.textBoxPassword.Text);
            }
        }

        string ITeamCityAccessConfiguration.UserName
        {
            [DebuggerStepThrough]
            get
            {
                return (this.textBoxUsername.Text);
            }
        }

        bool ITeamCityAccessConfiguration.UseSSL
        {
            get
            {
                return this.checkBoxUseSsl.Checked;
            }
        }

        bool ITeamCityAccessConfiguration.TrustSslCertificate
        {
            get
            {
                return this.checkBoxTrustSslCertificate.Checked;
            }
        }

        #endregion

        #region Nested type: Action

        private delegate void Action();

        #endregion

        private TeamCityProject SeletedProject
        {
            [DebuggerStepThrough]
            get
            {
                return this.listBoxProject.SelectedItem as TeamCityProject;
            }
        }

        private void OnButtonUpdateProjectsClick(object sender, EventArgs e)
        {
            this.UpdateProjects();
            this.UpdateVcsRoots();
            this.UpdateUsers();
            this.UpdateGroups();
        }

        private void UpdateProjects()
        {
            this.SafeExecute(() =>
            {
                this.listBoxProject.Items.Clear();
                this.listBoxProject.Items.AddRange(this.teamCityClient.GetAllProjects().ToArray());
            });
        }

        private void UpdateVcsRoots()
        {
            this.SafeExecute(() =>
            {
                this.listBoxVcsRoots.Items.Clear();
                this.listBoxVcsRoots.Items.AddRange(this.teamCityClient.GetAllVcsRoots().ToArray());
            });
        }

        private void UpdateUsers()
        {
            this.SafeExecute(() =>
            {
                this.listBoxUsers.Items.Clear();
                this.listBoxUsers.Items.AddRange(this.teamCityClient.GetAllUsers().ToArray());
            });
        }

        private void UpdateGroups()
        {
            this.SafeExecute(() =>
            {
                this.listBoxGroups.Items.Clear();
                this.listBoxGroups.Items.AddRange(this.teamCityClient.GetAllGroups().ToArray());
            });
        }

        private void OnListBoxProjectsSelectedIndexChanged(object sender, EventArgs e)
        {
            this.UpdateConfigurations();
        }

        private void UpdateConfigurations()
        {
            if (this.SeletedProject != null)
            {
                this.SafeExecute(() =>
                {
                    this.listBoxConfigurations.Items.Clear();
                    this.listBoxConfigurations.Items.AddRange(this.teamCityClient.GetBuildConfigurations(this.SeletedProject).ToArray());
                });
            }
        }

        private void OnListBoxConfigurationsSelectedIndexChanged(object sender, EventArgs e)
        {
            this.UpdateBuilds();
        }

        private void UpdateBuilds()
        {
            this.treeViewConfigurationsDetail.Nodes.Clear();
            var configuration = this.SelectedConfiguration;

            if (configuration != null)
            {
                this.SafeExecute(() =>
                {
                    this.listBoxBuilds.Items.Clear();
                    this.listBoxBuilds.Items.AddRange(this.teamCityClient.GetBuilds(configuration).Select(b => new BuildViewModel(b)).ToArray());

                    var treeNodeVcsRoots = new TreeNode("VcsRoots");
                    foreach (var vcsRootId in configuration.VcsRootIds)
                    {
                        treeNodeVcsRoots.Nodes.Add(string.Format(CultureInfo.InvariantCulture, "Id: {0}", vcsRootId));
                    }

                    this.treeViewConfigurationsDetail.Nodes.AddRange(new TreeNode[] { treeNodeVcsRoots });
                    this.treeViewConfigurationsDetail.ExpandAll();
                });
            }
        }

        private void UpdateBuildDetails()
        {
            this.treeViewBuildDetail.Nodes.Clear();
            var build = this.SelectedBuild;
            if (build != null)
            {
                this.SafeExecute(() =>
                {
                    var treeNodeTags = new TreeNode("Tags");
                    var treeNodePinInfo = new TreeNode("PinInfo");

                    build.Tags.ForEach(tag => treeNodeTags.Nodes.Add(tag));
                    
                    treeNodePinInfo.Nodes.Add(string.Format(CultureInfo.InvariantCulture, "Pinned: {0}", build.Pinned));
                    if (build.PinInfo != null)
                    {
                        treeNodePinInfo.Nodes.Add(string.Format(CultureInfo.InvariantCulture, "Timestamp: {0:G}", build.PinInfo.TimeStamp));
                        treeNodePinInfo.Nodes.Add(string.Format(CultureInfo.InvariantCulture, "Text: {0}", build.PinInfo.Text));
                    }

                    this.treeViewBuildDetail.Nodes.AddRange(new TreeNode[] { treeNodeTags, treeNodePinInfo });
                    this.treeViewBuildDetail.ExpandAll();
                });
            }
        }

        private void UpdateVcsRootsDetail()
        {
            this.listBoxVcsDetails.Items.Clear();
            var vcsRoot = this.SelectedVcsRoot;
            if (vcsRoot != null)
            {
                this.SafeExecute(() =>
                {
                    this.listBoxVcsDetails.Items.AddRange(vcsRoot.Properties.Select(root => string.Format(CultureInfo.InvariantCulture, "Name:{0}, Value:{1}", root.Key, root.Value)).ToArray());
                });
            }
        }

        private void UpdateUserDetail()
        {
            this.listBoxUserDetail.Items.Clear();
            var user = this.SelectedUser;
            if (user != null)
            {
                this.SafeExecute(() =>
                {
                    this.listBoxUserDetail.Items.Add(string.Format(CultureInfo.InvariantCulture, "Email:{0}", user.Email));
                    this.listBoxUserDetail.Items.AddRange(user.GroupKeys.Select(group => string.Format(CultureInfo.InvariantCulture, "Group:{0}", group)).ToArray());
                });
            }
        }

        private void UpdateGroupDetail()
        {
            this.listBoxGroupDetail.Items.Clear();
            var group = this.SelectedGroup;
            if (group != null)
            {
                this.SafeExecute(() =>
                {
                    this.listBoxGroupDetail.Items.AddRange(group.UserIds.Select(user => string.Format(CultureInfo.InvariantCulture, "UserId:{0}", user)).ToArray());
                });
            }
        }

        protected TeamCityBuildConfiguration SelectedConfiguration
        {
            [DebuggerStepThrough]
            get
            {
                return this.listBoxConfigurations.SelectedItem as TeamCityBuildConfiguration;
            }
        }


        protected TeamCityBuild SelectedBuild
        {
            [DebuggerStepThrough]
            get
            {
                BuildViewModel buildViewModel = this.listBoxBuilds.SelectedItem as BuildViewModel;
                if (buildViewModel != null)
                    return buildViewModel.Build;
                return null;
            }
        }

        protected TeamCityVcsRoot SelectedVcsRoot
        {
            [DebuggerStepThrough]
            get
            {
                return this.listBoxVcsRoots.SelectedItem as TeamCityVcsRoot;
            }
        }

        protected TeamCityUser SelectedUser
        {
            [DebuggerStepThrough]
            get
            {
                return this.listBoxUsers.SelectedItem as TeamCityUser;
            }
        }

        protected TeamCityGroup SelectedGroup
        {
            [DebuggerStepThrough]
            get
            {
                return this.listBoxGroups.SelectedItem as TeamCityGroup;
            }
        }

        private void listBoxBuilds_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.UpdateBuildDetails();
        }

        private void listBoxVcsRoots_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.UpdateVcsRootsDetail();
        }

        private void listBoxUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.UpdateUserDetail();
        }

        private void listBoxGroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.UpdateGroupDetail();
        }

    }
}